import { NextFunction, Request, Response } from "express";
import { UserService } from "../services";
import { AppError } from "../utils";
import { verify } from "jsonwebtoken";
import { config } from "dotenv";

config();

const jwtSecret = process.env.JWT_SECRET;

export const deserializeUser = async (
  req: Request,
  res: Response,
  next: NextFunction,
) => {
  try {
    let token = "";
    if (
      req.headers.authorization &&
      req.headers.authorization.startsWith("Bearer")
    ) {
      token = req.headers.authorization.split(" ")[1];
    } else if (req.cookies.token) {
      token = req.cookies.token;
    }
    if (!token) {
      return next(new AppError(401, "You are not logged in"));
    }
    const decoded = verify(token, jwtSecret);
    if (!decoded || !(typeof decoded === "object")) {
      return next(new AppError(401, `Invalid token or user doesn't exist`));
    }
    const user = await UserService.findById(decoded.data.id);
    if (!user) {
      return next(new AppError(401, `Invalid token or session has expired`));
    }
    res.locals.user = user;
    next();
  } catch (err) {
    next(err);
  }
};
